package Deom1;

import com.mysql.cj.jdbc.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;

public class DataSource extends MysqlDataSource {
    public static void main(String[] args) {
        //定义数据源对象
     MysqlDataSource dataSource=new MysqlDataSource();
     //设置数据库连接串
dataSource.setURL("jdbc:mysql://127.0.0.1:3306/exam?characterEncoding=utf8&allowPublicKeyRetrieval" +
        "=true&useSSL=false");
//用户名
dataSource.setUser("root");
//密码
dataSource.setPassword("123456");
Connection connection=null;
PreparedStatement statement=null;
ResultSet resultSet=null;
        try {
            //通过数据源获取数据库连接
           connection= dataSource.getConnection();
           //获取预处理SQL执行对象
            //定义要执行的SQL
           String sql="select id,name,class_id from student where name=?";
          statement= connection.prepareStatement(sql);
          //接收用户输入
            System.out.println("请输入学生姓名：");
            Scanner scanner=new Scanner(System.in);
            String name=scanner.next();
            //用真实值替换占位符
            statement.setString(1,name);
//执行sql语句，获取结果集
        resultSet= statement.executeQuery();
//遍历结果集
            while (resultSet.next()){
                int id=resultSet.getInt(1);
                String Name=resultSet.getString(2);
                int class_id=resultSet.getInt(3);
                System.out.println(MessageFormat.format("学生编号={0}，学生姓名={1},班级编号={3}",id,Name,class_id));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            if (resultSet!=null){
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement!=null){
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection!=null){
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
